<?php

namespace App\Services\Relation;

use App\Models\User;

class UserTreeService
{
    public static function make($userId = 0)
    {
        // 获取所有用户并按 parent_id 分组
        $users = User::query()
            ->select([
                'id', 'parent_id', 'is_group_leader'
            ])
            ->get()
            ->groupBy('parent_id');

        // 生成树形结构字符串
        $tree = self::buildTree($userId, $users, 0);

        return $tree;
    }

    private static function buildTree($userId, $users, $level)
    {
        // 获取当前用户信息
        $user = User::find($userId);

        // 判断用户是否是组长
        $isGroupLeader = $user ? $user->is_group_leader : false;
        $leaderMarker = $isGroupLeader ? " [GroupLeader]" : "";

        // 用于存储树形结构
        $tree = str_repeat("|__ ", $level) . sprintf("%s%s", $userId, $leaderMarker) . "\n";

        // 获取当前用户的子用户
        if (isset($users[$userId])) {
            foreach ($users[$userId] as $childUser) {
                $tree .= self::buildTree($childUser->id, $users, $level + 1);
            }
        }

        return $tree;
    }
}
